package com.lenovo.smarttraffic.zm_user_module;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ViewDragHelper;
import android.support.v4.widget.ViewDragHelper.Callback;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

/**
 * author  张猛
 **/
public class DragLayout extends FrameLayout {
    String TAG = "DragLayout";

    public static Status statusDrag = Status.Close;
    private Status preStatus = Status.Close;

    private ViewDragHelper mDragHelper;
    private OnDragStatusListener listener;

    private boolean smooth = true;


    private View HiddenView;
    private View ItemView;


    private int hiddenViewWidth;
    private int hiddenViewHeight;
    private int itemWidth;
    private int itemHeight;

    public DragLayout(@NonNull Context context) {
        super(context);
    }

    public DragLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mDragHelper = ViewDragHelper.create(this, callback);
    }

    Callback callback = new Callback() {
        //尝试捕获被拖拽View
        @Override
        public boolean tryCaptureView(@NonNull View child, int pointerId) {
            return child == ItemView;
        }

        //决定拖拽View在水平方向上应该移动的距离    与拖动多少自动弹出无关
        @Override
        public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {
            if (child == ItemView) {
                if (left > 0) {
                    return 0;
                } else {
                    left = Math.max(left, -hiddenViewWidth);
                    return left;
                }
            }
            return 0;
        }

        //child  的水平拖拽范围
        @Override
        public int getViewHorizontalDragRange(@NonNull View child) {
            return hiddenViewWidth;
        }

        //当view 拖拽位置发生改变时的回调
        @Override
        public void onViewPositionChanged(@NonNull View changedView, int left, int top, int dx, int dy) {
            if (ItemView == changedView) {
//                将View沿水平正方向偏移dx    想👉为正
                HiddenView.offsetLeftAndRight(dx);
            }
            invalidate();
        }


        // 手指离开当前捕获的View的时候，会回调这个方法
        @Override
        public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) {
            //手指离时 x轴现在位置 与 原来位置   的差值   想👉为正
            if (releasedChild == ItemView) {
                Log.e(TAG, "setStatus: " + Status.Open.toString());
                if (xvel == 0 && Math.abs(ItemView.getLeft()) > hiddenViewWidth / 3.0f) {
                    open(smooth);
                } else if (xvel < 0) {
                    open(smooth);
                } else {
                    close(smooth);
                }
            }
        }
    };


    public void setDragStatusListener(OnDragStatusListener listener) {
        this.listener = listener;
    }

    public interface OnDragStatusListener {
        void onStatusChanged(Status status);

        void onStartCloseAnimation();

        void onStartOpenAnimation();
    }


    public enum Status {
            Open, Close
    }

    public void setStatus(Status status, boolean smooth) {
        //statusDrag
        this.statusDrag = status;
        if (status == Status.Open) {
            open(smooth);
        } else {
            close(smooth);
        }
    }

    /**
     * 是否设置过渡动画
     *
     * @param smooth
     */
    public void setSmooth(boolean smooth) {
        this.smooth = smooth;
    }

    private void close(boolean smooth) {
        preStatus = statusDrag;
        statusDrag = Status.Close;
        if (smooth) {
            if (mDragHelper.smoothSlideViewTo(ItemView, 0, 0)) {
                if (listener != null) {
                    listener.onStartCloseAnimation();
                }
                ViewCompat.postInvalidateOnAnimation(this);
            }
        } else {
            layout(statusDrag);
        }
        if (listener != null && preStatus == Status.Open) {
            listener.onStatusChanged(statusDrag);
        }
    }

    private void open(boolean smooth) {
        preStatus = statusDrag;
        statusDrag = Status.Open;
        if (smooth) {
            if (mDragHelper.smoothSlideViewTo(ItemView, -hiddenViewWidth, 0)) {
                if (listener != null) {
                    listener.onStartOpenAnimation();
                }
                //android中实现view的更新有两组方法，一组是invalidate，
                // 另一组是postInvalidate，其中前者是在UI线程自身中使用，而后者在非UI线程中使用。
                ViewCompat.postInvalidateOnAnimation(this);
            }
        } else {
            layout(statusDrag);
        }
        if (listener != null && preStatus == Status.Close) {
            listener.onStatusChanged(statusDrag);
        }
    }

    private void layout(Status status) {
        if (status == Status.Close) {
            HiddenView.layout(itemWidth, 0, itemWidth + hiddenViewWidth, itemHeight);
            ItemView.layout(0, 0, itemWidth, itemHeight);
        } else {
            HiddenView.layout(itemWidth - hiddenViewWidth, 0, itemWidth, itemHeight);
            ItemView.layout(-hiddenViewHeight, 0, itemWidth - hiddenViewWidth, itemHeight);
        }
    }


    @Override
    public void computeScroll() {
        super.computeScroll();
        if (mDragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(this);
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        final int action = ev.getAction();
        if (action == MotionEvent.ACTION_CANCEL) {
            mDragHelper.cancel();
            return false;
        }
        return mDragHelper.shouldInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mDragHelper.processTouchEvent(event);
        return true;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        ItemView = getChildAt(1);
        HiddenView = getChildAt(0);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        itemWidth = ItemView.getMeasuredWidth();
        itemHeight = ItemView.getMeasuredHeight();
        hiddenViewWidth = HiddenView.getMeasuredWidth();
        hiddenViewHeight = HiddenView.getMeasuredHeight();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        layout(Status.Close);
    }
}
